import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Paper,
    Select, Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow, Typography
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import {DatePicker} from '@mui/x-date-pickers/DatePicker';

import {list as listTeacher} from "../../api/info/teacher";
import {history} from "../../api/lesson/lesson-schedule";
import RefreshIcon from '@mui/icons-material/Refresh';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import ExpandIcon from '@mui/icons-material/Expand';
import CompressIcon from '@mui/icons-material/Compress';

import {RestartAlt} from "@mui/icons-material";

import {formatMoney} from "../../utils/math";

import dayjs from "dayjs";
import LoadingButton from "@mui/lab/LoadingButton";
import PageNavBar from "../common/page-nav-bar";
import {useSelector} from "react-redux";

import {YYYYMMDD, formatDate} from "../../utils/time";

const defaultForm = {
    page: 1,
    start: dayjs().startOf('month').startOf('day'),
    end: dayjs().startOf('day'),
    teacherId: 0,
};
Object.freeze(defaultForm);

function LessonHistory() {

    const user = useSelector(state => state.auth.user);

    const [principal, setPrincipal] = useState(false);

    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);

    const [form, setForm] = useState({...defaultForm});

    const [loading, setLoading] = useState(false);
    const [histories, setHistories] = useState([]);

    const [teachers, setTeachers] = useState([]);

    const [searching, setSearching] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [dense, setDense] = useState(false);

    function loadHistory(query) {
        setLoading(true);

        history({
            ...query,
            start: formatDate(query.start),
            end: formatDate(query.end),
        }).then(data => {

            setTotal(data.total);
            setPage(data.page);
            setSize(data.size);

            data.list.forEach(e => {
                const students = JSON.parse(e.students);
                e.studentNames = students.map(s => s.name).join(', ');
            })
            setHistories(data.list);

            setLoading(false);
            setSearching(false);
        });
    }

    function loadTeacher() {
        listTeacher().then(data => {
            setTeachers(data || []);
        });
    }

    useEffect(() => {
        loadHistory(defaultForm);
        loadTeacher();
        setPrincipal(user.role === 'PRINCIPAL');
    }, [user.role]);

    function handleChange(event) {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    }

    return (
        <Box p={4} display="flex" gap={4} flexDirection="column">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '100%'}}>
                <CardHeader
                    title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">授课历史</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>}
                    action={
                        <Box mr={1}>
                            <IconButton onClick={() => setShowForm(!showForm)}>
                                {showForm ? <VisibilityOffIcon/> : <VisibilityIcon/>}
                            </IconButton>

                            <IconButton onClick={() => setDense(!dense)}>
                                {dense ? <ExpandIcon/> : <CompressIcon/>}
                            </IconButton>

                            <IconButton onClick={() => loadHistory(form)}><RefreshIcon/></IconButton>
                        </Box>
                    }/>

                <CardContent>
                    {showForm && <Box mb={4} display="flex" gap={2} alignItems="center" flexWrap="wrap">
                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="开始日期" value={form.start}
                                    onChange={v => setForm({...form, start: v})}/>

                        <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                    label="结束日期" name="end" value={form.end}
                                    onChange={v => setForm({...form, end: v})}/>

                        {principal && <FormControl sx={{width: 180}}>
                            <InputLabel>授课老师</InputLabel>
                            <Select value={form.teacherId} label="授课老师" name="teacherId" onChange={handleChange}>
                                <MenuItem value="0">选择授课老师</MenuItem>
                                <Divider/>
                                {teachers.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>}

                        <Button startIcon={<RestartAlt/>} variant="contained" color="primary"
                                onClick={() => setForm({...defaultForm})}>
                            重置
                        </Button>
                        <LoadingButton startIcon={<SearchIcon/>} variant="contained" color="primary"
                                       type="submit" loading={searching}
                                       loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                       onClick={() => {
                                           setSearching(true);

                                           const updatedForm = {...form, page: 1};
                                           setForm(updatedForm);
                                           loadHistory(updatedForm);
                                       }}>查询</LoadingButton>
                    </Box>}

                    <TableContainer component={Paper}>
                        <Table size={dense ? 'small' : 'medium'}>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell>课程</TableCell>
                                    <TableCell>班级</TableCell>
                                    {principal && <TableCell>教师</TableCell>}
                                    <TableCell width={'160px'}>学员</TableCell>
                                    <TableCell align={"center"} width={'120px'}>薪酬（元）</TableCell>
                                    <TableCell width={'160px'} align={"center"}>时间</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {histories.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.course.name}</TableCell>
                                        <TableCell>{e.classGroupName}</TableCell>
                                        {principal && <TableCell>{e.teacher.name}</TableCell>}
                                        <TableCell>{e.studentNames}</TableCell>
                                        <TableCell align={"center"}>{formatMoney(e.teacherSalary)}</TableCell>
                                        <TableCell align={"center"}>{e.lessonTime}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    {total > size && <TablePagination
                        ActionsComponent={PageNavBar}
                        rowsPerPageOptions={[10]}
                        component="div"
                        count={total}
                        rowsPerPage={size}
                        page={page - 1}
                        labelDisplayedRows={({count, page}) =>
                            `第 ${page + 1} 页，共 ${Math.ceil(total / size)} 页，共 ${count} 条数据`}
                        onPageChange={(event, newPage) => {
                            window.scrollTo(0, 0);
                            const updatedForm = {...form, page: newPage + 1};
                            setForm(updatedForm);
                            loadHistory(updatedForm);
                        }}
                    />}
                </CardContent>
            </Card>
        </Box>
    );
}

export default LessonHistory;
